package pjaws.paw;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import pjaws.PjawsConstants;

/**
 * PawServerSocket handles connections from other PaWs. Once a socket is
 * accepted, the socket is added as a receive socket for the Paw that owns this
 * PawServerSocket.
 * 
 * @author Zachary Cancio
 * 
 */

public class PawServerSocket extends Thread {
	private Paw myPaw;
	private ServerSocket mySS;

	public PawServerSocket(Paw p) throws IOException {
		myPaw = p;
		mySS = new ServerSocket(PjawsConstants.PAWPORT);
	}

	public void run() {
		try {
			while (true) {
				Socket s = mySS.accept();
				BufferedInputStream bis = new BufferedInputStream(s
						.getInputStream());
				DataInputStream dis = new DataInputStream(bis);
				String cmd = Paw.getInputString(dis, PjawsConstants.CMDLEN);
				// TODO need a better way to determine which paw is connecting
				if (cmd.equals(PjawsConstants.PAWID)) {
					int PawId = dis.readInt();
					System.out.println("Received request from " + PawId);
					myPaw.addReceiveSocket(PawId, s);

				} else {
					s.close();
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
